package com.tech.koufu.ui.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.VolleyError;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.StockInfo; 
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics; 
import com.tech.koufu.ui.activity.BuyStocksActivity;
import com.tech.koufu.ui.adapter.StocksGridItemAdapter; 
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshGridView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.content.Context; 
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView; 
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class HotStocksFragment extends Fragment {
	private static final String TAG = "HotStocksFragment";
	private int page = 1;
	private Context mContext;
	private View rootView;
	private PullToRefreshGridView mPullToRefreshGridView;
	private GridView actualGridView;
//	CookieStringRequest stringRequest;
//	private RequestQueue mQueue;
	private StocksGridItemAdapter mAdapter;
	private Context context;
	private ArrayList<StockInfo> datas;
	private MyApplication myApp;
	private Object ncode;

	public static HotStocksFragment newInstance(int tabid) {
		HotStocksFragment array = new HotStocksFragment();
		Bundle args = new Bundle();
		args.putInt("tabid", tabid);
		array.setArguments(args);
		return array;
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater
					.inflate(R.layout.fragment_choose_viewpager_stocks,
							container, false);
			context = getActivity().getApplicationContext();
			myApp = (MyApplication) getActivity().getApplication();
			initView();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		mContext = this.getActivity();
		return rootView;
	}
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(mContext);       //统计时长
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(mContext);
	}
	
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);  
		initData();
	}

	private void initData() {
		datas = new ArrayList<StockInfo>();
		mAdapter = new StocksGridItemAdapter(context, datas);
//		mQueue = Volley.newRequestQueue(context);  
		mPullToRefreshGridView.setAdapter(mAdapter);
		mPullToRefreshGridView.setOnRefreshListener(new OnRefreshListener<GridView>() {

			@Override
			public void onRefresh(PullToRefreshBase<GridView> refreshView) {  
				Mode mode = mPullToRefreshGridView.getCurrentMode();  
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
				load();
			}
		}); 
		load();
	}

	private void initView() {
		mPullToRefreshGridView = (PullToRefreshGridView) rootView
				.findViewById(R.id.gv_scs);
		actualGridView = mPullToRefreshGridView.getRefreshableView();
		registerForContextMenu(actualGridView);
		actualGridView.setOnItemClickListener(itemClick);
	}

	private void load() {
		String url = Statics.URL_PHP+Statics.IF_hotstock;  
		CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url,
				new Listener<String>() {

					@Override
					public void onResponse(String response) {
//						Log.w(TAG, response);
						if(!TextUtils.isEmpty(response)){
							JSONObject res;
							try {
								res = new JSONObject(response); 
								int status = res.optInt("status");
								if(status==0){
									JSONArray array = res.getJSONArray("data");
									int length = array.length();
									StringBuilder sb = new StringBuilder();
									for(int i=0;i<length;i++){
										JSONObject obj = array.optJSONObject(i);
										StockInfo stockInfo = new StockInfo();
										String code = obj.optString("code");
										if(code.startsWith("sz")){
											code = code.substring(2);
										}
										stockInfo.setCode(code);
										stockInfo.setName(obj.optString("name"));
//										datas.add(stockInfo);
										sb.append(KouFuTools.getNcode(code)).append(",");
									}
									ncode = sb.toString();
									loadBinData();
								}else{
									
								}
								
							} catch (JSONException e) { 
								e.printStackTrace();
							}
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						error.printStackTrace();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page + "");
				params.put("userID", myApp.getUserid());
				return params;
			}
		};
		stringRequest.setHeader(myApp.phpsessid);
		stringRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(mContext).addToRequestQueue(stringRequest); 
	}
	public void loadBinData() {
		if(ncode==null)
			return; 
		String url = Statics.URL_2 + Statics.URL_BinStock + ncode
				+ "&field=ZG,ZD,ZX,ZSP";
//		Log.v(TAG, "URL_BinStock="+url);
		CookieStringRequest stringRequest = new CookieStringRequest(url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
//					Log.v(TAG, "URL_BinStock="+response);
					if(response!=null){
						String[] rs = response.split(";");
						for(String results : rs){
							String[] result = results.split(",");
							if(result.length<5){
								continue;
							}
							StockInfo stockInfo = new StockInfo();
							stockInfo.setName(result[1].trim());
							stockInfo.setCode(result[0].trim());
							stockInfo.setZg(result[2].trim());
							stockInfo.setZd(result[3].trim());
							stockInfo.setZx(result[4].trim());
							stockInfo.setZsp(result[5].trim());
							datas.add(stockInfo);
						}
					} 
					mAdapter.datas = datas;
					mAdapter.notifyDataSetChanged();
					mPullToRefreshGridView.onRefreshComplete();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
				mPullToRefreshGridView.onRefreshComplete();
			}
		});
		stringRequest.setCharset("GBK");
		stringRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(mContext).addToRequestQueue(stringRequest); 
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {  
			Intent intent = new Intent(getActivity(), BuyStocksActivity.class);
			intent.putExtra("stockInfo", datas.get(position));
			intent.putExtra("datatype", 1);
			intent.putExtra("parsetype", 1);
			startActivity(intent);
			getActivity().finish();
		}
	};
	public void onStop() {
		super.onStop();
		RequestQueueSingleton.getInstance(mContext).cancleAllReq(TAG);
	};
}
